/*
 * @Date: 2023-02-27 21:25:55
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-27 16:56:04
 * @FilePath: \A19\frontend\src\hooks\world\keyActions.ts
 */
import mitt from "@/mitt";
import { ServiceType } from "@/shared/protocols/serviceProto";
import { keyboard, Lingo, useLoop } from 'lingo3d-vue';
import { WsClient } from "tsrpc-browser";
import { Ref, ref, onMounted, onUnmounted } from "vue";

export function keyActionshook(foxRef: Ref<Lingo.Dummy | undefined>,
    currentUser: {
      _id: string;
      role: string;
      school: string;
      name: string;
      portrait: string;
      email: string;
      number: string;
      gender: number;
    },
    wsClient:WsClient<ServiceType> | undefined,
    courseId:string
  ) {

  let currentKeys = new Set<string>
  const stopWalk = ref(false);
  const keyActions = (char:'fox' | 'person') => {

    keyboard.onKeyPress = (_, keys) => {
      // console.log(e.keys);
      if (stopWalk.value) return;

      const fox = foxRef.value;
      if (!fox) return;

      currentKeys = keys

      if (keys.has("w")) fox.strideForward = -5;
      else if (keys.has("s")) fox.strideForward = 5;
      else fox.strideForward = 0;

      if (keys.has("a")) fox.strideRight = 5;
      else if (keys.has("d")) fox.strideRight = -5;
      else fox.strideRight = 0;

      const { animation,rotationX,rotationY,rotationZ,x,y,z,strideForward,strideRight } = fox
      wsClient?.sendMsg('AMessages/Game/UpdateStatus',{
        liveId:courseId,
        playerId:currentUser._id,
        playerName:currentUser.name,
        x,
        y,
        z,
        strideForward,
        strideRight,
        animation:animation?.toString() || 'idle',
        rotationX,
        rotationY,
        rotationZ,
        model:char
      })
    };
  };

  // const sync = useLoop(() =>{
  //   const fox = foxRef.value
  //   if (!fox) return

  //   // console.log(currentKeys.has('w'),currentKeys.has('a'),currentKeys.has('s'),currentKeys.has('d'),);
  //   const { animation,rotationX,rotationY,rotationZ } = fox
  //   // console.log(animation?.toString(),rotationX,rotationY,rotationZ);
  //   wsClient?.sendMsg('AMessages/Game/UpdateStatus',{
  //     live:courseId,
  //     userId:currentUser._id,
  //     username:currentUser.name,
  //     w:currentKeys.has('w'),
  //     a:currentKeys.has('a'),
  //     s:currentKeys.has('s'),
  //     d:currentKeys.has('d'),
  //     animation:animation?.toString() || 'idle',
  //     rotationX,
  //     rotationY,
  //     rotationZ
  //   })
  // })

  onMounted(() => {
    mitt.on("stopwalk", (stop) => {
      stopWalk.value = stop as boolean;
    });
  });
  onUnmounted(() => {
    mitt.off("stopwalk");
  });

  return {
    stopWalk,
    keyActions,
  };
}
